﻿using System;
using System.Collections;
using System.Linq;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using ZhukBlogLinqExamples.Repositories;

namespace ZhukBlogLinqExamples.FieldTypes.Employee.Controls
{
    public class EmployeePicker : EntityEditorWithPicker
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PickerDialogType = typeof(EmployeePickerDialog);
            MultiSelect = CustomProperty == "1";
            var ctx = SPContext.Current;
            SiteId = ctx.Site.ID;
            WebId = ctx.Web.ID;
            WebUrl = ctx.Web.Url;
            Height = new Unit(100, UnitType.Percentage);
            CssClass = "ms-usereditor";
        }

        private Guid SiteId { get; set; }
        private Guid WebId { get; set; }
        private string WebUrl { get; set; }

        public override PickerEntity ValidateEntity(PickerEntity entity)
        {
            if (entity == null) return null;
            if (entity.IsResolved)
            {
                return entity;
            }
            //SPSecurity.RunWithElevatedPrivileges(
            //    () =>
            //    {
            //        var repository = new EmployeeRepository(WebUrl);
            //        var emps = repository.SearchEmployees(entity.DisplayText);
            //        if (emps.Count() == 1)
            //        {
            //            entity = emps.First().ToPickerEntity();
            //        }
            //        else
            //        {
            //            entity.IsResolved = false;
            //        }
            //    });
            return entity;
        }

        protected override PickerEntity[] ResolveErrorBySearch(string unresolvedText)
        {
            var res = new PickerEntity[] { };
            //SPSecurity.RunWithElevatedPrivileges(
            //    () =>
            //    {
            //        var repository = new EmployeeRepository(WebUrl);
            //        var emps = repository.SearchEmployees(unresolvedText);
            //        res = emps.Select(e => e.ToPickerEntity()).ToArray();
            //    });
            return res;
        }

        public override string DialogTitle
        {
            get
            {
                return "Employee Search";
            }
            set
            {
                base.DialogTitle = value;
            }
        }

        public new void UpdateEntities(ArrayList list)
        {
            base.UpdateEntities(list);
        }
    }
}
